<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="700"
    :minHeight="300">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { BasicModal } from '@/components/Modal';
import { useModalInner } from '@/components/Modal/src/hooks/useModal';
import { ModalMethods } from '@/components/Modal/src/typing';
import { BasicForm, useForm } from '@/components/Form';
import { computed, ref, unref } from 'vue';
import userUserData from './user.data';
import { useOptions, useDict } from '@/hooks/web/useOptions';
import { getRoles } from '@/api/system/role'
import { getOrganizationTree } from '@/api/unit/organization';
import { userFormSchema } from './user.data2';
import { getPositions } from '@/api/unit/positions';
import { Recordable } from '/#/global';
import { saveOrUpdateUser } from '@/api/system/user';
import { convertSelectOptions } from '@/utils/convert';


// 方式一,在初始化加载下拉列表的选项,只是适用简单下拉，不适合树节点,必须和节点对应
// const { userFormSchema, setUserFormOptions, setRoleOptions } = userUserData()
// useOptions(setUserFormOptions, undefined, ['user_status'])
// useOptions(setRoleOptions, findRoleAllName)




const { getDicts } = useDict(['user_status'])
const dicts = await getDicts()

const emit = defineEmits<{
  (e: 'register', modalMethod: ModalMethods, uuid: string): void,
  (e: 'success', o: Recordable): void
}>()

const isUpdate = ref(true);
const rowId = ref('');
const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));


const [registerForm, { setFieldsValue, resetFields, updateSchema, validate }] = useForm({
  labelWidth: 100,
  schemas: userFormSchema,
  componentMinWidth: 220

})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ loading: true });
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  // 方式2 ，在这里更新选项
  const organizationTree = await getOrganizationTree()

  const roleOptions = await getRoles()

  console.log(organizationTree)
  const positionOptions = await getPositions();


  updateSchema([
    {
      field: 'organizations',
      componentProps: {
        data: organizationTree
      }
    },
    {
      field: 'roles',
      componentProps: {
        options: roleOptions
      },
    },
    {
      field: 'positions',
      componentProps: {
        options: positionOptions
      },
    },
    {
      field: 'enabled',
      componentProps: {
        options: dicts.user_status,
      },
    }

  ])

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
    });
  } else {
    rowId.value = ''
  }


  setModalProps({ loading: false });

});


async function handleSubmit() {
  try {
    // callback?: (isValid: boolean, invalidFields?: ValidateFieldsError)
    const values = await validate();

    console.log(values)
    // 这里来请求api

    await saveOrUpdateUser({ ...values, id: rowId.value })

    setModalProps({ confirmLoading: true })
    closeModal();
    emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value, state: values['enabled'] === '1' } });

  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>

<style lang="scss">
</style>